﻿using NetCourse.Framework.Security;
using System.Runtime.InteropServices;
using System.Text;
using XmuAuthen.Models;
using System.Timers;
using NetCourse.Framework;

namespace XmuAuthen.Services
{
    public class CredentialManager: ISingletonDependency   // 单例模式: 仅有一个管理器
    {
        protected Dictionary<string,Certification> Cache {  get; set; } = new Dictionary<string,Certification>();

        public string test = "test";

        public CredentialManager()  // 构造函数: 启动清理过期证书的定时器
        {
            CleanTimer();
        }

        public string GetCredential(IUserPrincipal user)
        {
            string key = GenerateKey();
            Certification cert = new(user,DateTime.Now.AddHours(1));    // 证书有效期为1小时
            //Certification cert = new(user, DateTime.Now.AddMinutes(1));    // 测试：证书有效期为1分钟
            Cache.Add(key,cert);

            Console.WriteLine(Cache[key].ExpiredOn.ToString());

            return key;
        }

        public IUserPrincipal? GetUser(string key)
        {
            Console.WriteLine(Cache.Count());
            
            if (Cache.ContainsKey(key))
            {
                Certification cert = Cache[key];
                if (cert.ExpiredOn > DateTime.Now)  // 证书未过期
                {
                    return cert.UserPrincipal;
                }
                else                                // 证书已过期
                {
                    Cache.Remove(key);
                    return null;
                }
            }
            return null;
        }
        public void RemoveCredential(string key)
        {
            Cache.Remove(key);
        }

        public int testCount()
        {
            return Cache.Count();
        }

        private string GenerateKey()
        {
            string charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            StringBuilder res = new StringBuilder();
            int setLength = charSet.Length;
            Random random = new Random();
            int length = random.Next(8, 13);    // 生成的字符串长度为8-12位

            for (int i = 0; i < length; i++)
            {
                res.Append(charSet[random.Next(0, setLength)]);
            }

            return res.ToString();
        }

        private void CleanTimer()
        {
            Console.WriteLine("CleanTimer");
            System.Timers.Timer timer = new System.Timers.Timer(); 
            timer.Enabled = true;
            timer.Interval = 1000 * 60;     // 1分钟清理一次
            timer.Start();
            timer.Elapsed += new ElapsedEventHandler(CleanCache);
        }
        private void CleanCache(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("CleanCache");
            if (Cache != null)
            {
                foreach (var item in Cache)
                {
                    if (item.Value.ExpiredOn < DateTime.Now)    // 证书已过期
                    {
                        Cache.Remove(item.Key);
                    }
                }
            }
        }
    }
}
